package com.yksj.healthtalk.ui.doctorstation;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.universalimageloader.core.ImageLoader;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.comm.ZoomImgeDialogFragment;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.DoctorOrderDeatils;
import com.yksj.healthtalk.entity.DoctorPatient;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.doctor.DoctorServiceActivity;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.TimeUtil;
import com.yksj.healthtalk.utils.ToastUtil;
import com.yksj.healthtalk.utils.ViewFinder;
import com.yksj.healthtalk.utils.ViewUtils;
/**
 * 我的患者 延时或者停止服务
 *
 */
public class DoctorServiceDelayOrStop extends Fragment implements OnClickListener {

	public TextView titleTextV;
	private View mView;
	private Button delayButton;
	private String Type="";
	private DoctorOrderDeatils deatils;
	private DoctorPatient mEntity;
	private TextView mTuiDingContent;//退订内容
	private final String LOOK_CONTENT="findcustomerBackOrder";//查看订单
	private final String SUMINT_EXIT="doctorBackOrder";//同意退回
	private final String SUMINT_REFUSE="updateOrderStatus";//拒绝退回
	private String mOrderId;//订单号
	private String mCustomerId;//患者ID
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.doctor_service_delayorstop, null);
		initView();
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mEntity = (DoctorPatient) getArguments().getSerializable("entity");
		if(mEntity!=null){
			mTuiDingContent = (TextView) mView.findViewById(R.id.tuiding_content);
			mOrderId = mEntity.getOrderId();
			mCustomerId = mEntity.getCustomerId();
			initData(mOrderId,mCustomerId);
		}
	}
	
	private void initView() {
		delayButton = (Button) mView.findViewById(R.id.delay_button);
		delayButton.setOnClickListener(this);
		mView.findViewById(R.id.title_back).setOnClickListener(this);
		mView.findViewById(R.id.service_content).setOnClickListener(this);
	}
	
	private void initDataView(DoctorOrderDeatils deatils){
			ViewFinder viewFinder=new ViewFinder(mView);
		if(!TextUtils.isEmpty(deatils.getSERVICE_ITEM_DESC().trim()))
			viewFinder.setText(R.id.doctor_desc, deatils.getSERVICE_ITEM_DESC());
		if(!TextUtils.isEmpty(deatils.getSERVICE_CONTENT().trim()))
		    viewFinder.setText(R.id.service_content1, deatils.getSERVICE_CONTENT());
		
		//服务类型
		viewFinder.setText(R.id.service_type,deatils.getSERVICE_TYPE_SUB());
		
		if(TextUtils.isEmpty(deatils.getSERVICE_START().trim())){
			String start_T=TimeUtil.getFormatTime(deatils.getORDER_CREATE_TIME());
			viewFinder.setText(R.id.start_time,start_T.substring(0, start_T.length()-3));
			
		}else{
			String start_T=TimeUtil.getFormatTime(deatils.getSERVICE_START());
			viewFinder.setText(R.id.start_time,start_T.substring(0, start_T.length()-3));
		}
		
		TextView serviceEndTime=(TextView) mView.findViewById(R.id.end_time);
		if(TextUtils.isEmpty(deatils.getSERVICE_END().trim())){//end_time_line
			 mView.findViewById(R.id.end_time_line).setVisibility(View.GONE);
		}else{
			String end_T=TimeUtil.getFormatTime(deatils.getSERVICE_END());
			serviceEndTime.setText(end_T.substring(0, end_T.length()-3));	
		}
		
		TextView titleTextV = (TextView)mView.findViewById(R.id.title_lable);
		titleTextV.setText(deatils.getSERVICE_TYPE());
		
		TextView titleMiaoshu = (TextView)mView.findViewById(R.id.miaoshu_title_text);
		if("1".equals(deatils.getSERVICE_TYPE_ID())){
			titleMiaoshu.setText(getString(R.string.common_sevice));
		}else if("2".equals(deatils.getSERVICE_TYPE_ID())){
			titleMiaoshu.setText(getString(R.string.time_service));
		}else if("3".equals(deatils.getSERVICE_TYPE_ID())){
			titleMiaoshu.setText(getString(R.string.time_service));
		}
		//服务价格
		TextView servicePrice=(TextView) mView.findViewById(R.id.service_price);
		servicePrice.setText(deatils.getSERVICE_GOLD()+"元");//+"元/人"
		TextView prompt= (TextView) mView.findViewById(R.id.prompt);
		mView.findViewById(R.id.chat_button).setOnClickListener(this);
		String strName=(!TextUtils.isEmpty(mEntity.getCustomerNickname()))?mEntity.getCustomerNickname():mEntity.getCustomerAccounts();
		switch (Integer.valueOf(deatils.getSERVICE_STATUS())) {
		case 10://未支付
			delayButton.setVisibility(View.GONE);
			mView.findViewById(R.id.chat_button).setVisibility(View.GONE);
			break;
		case 160:
		case 170://查看详情
			delayButton.setVisibility(View.GONE);
			mView.findViewById(R.id.chat_button).setVisibility(View.VISIBLE);
			break;
		case 150://Type=AgreedToDelay  Type=RefusedToDelay 延时请求
			Type="AgreedToDelay";
			delayButton.setText("同意延时服务请求");
			delayButton.setBackgroundResource(R.drawable.login_button);
			prompt.setVisibility(View.VISIBLE);
			prompt.setText("客户"+strName+"向您申请延时请求，请您及时处理!");
			mView.findViewById(R.id.refuse_delay_button).setVisibility(View.VISIBLE);
			mView.findViewById(R.id.refuse_delay_button).setOnClickListener(this);
			break;
		case 60://退订请求
			prompt.setVisibility(View.VISIBLE);
			prompt.setText(strName+"向您申请退订请求，请您及时处理!");
			mView.findViewById(R.id.agree_tuiding).setOnClickListener(this);
			mView.findViewById(R.id.tuiding_line).setVisibility(View.VISIBLE);
			mView.findViewById(R.id.refuse_tuiding).setOnClickListener(this);
			delayButton.setVisibility(View.GONE);
			//添加退订请求的图片
			mView.findViewById(R.id.tuiding_pic_line).setVisibility(View.VISIBLE);
			break;
		case 185://停止服务  Type=DoctorStopService
			Type="DoctorStopService";
			delayButton.setText("停止服务");
			mView.findViewById(R.id.chat_button).setVisibility(View.VISIBLE);
			mView.findViewById(R.id.chat_button).setOnClickListener(this);
			break;
		case 175:
		case 180://取消原因
			delayButton.setVisibility(View.GONE);
			break;
		case 70:
		case 155://155表示医生拒绝延时服务  (医生有权利主动延时)       Type=AgreedToDelay
			if("0".equals(deatils.getEXTEND_FLAG())){
				delayButton.setText("延时服务");
				 Type="DoctorsActiveDelay";
			}else{
				delayButton.setVisibility(View.GONE);	
			}
			 mView.findViewById(R.id.chat_button).setVisibility(View.VISIBLE);
				mView.findViewById(R.id.chat_button).setOnClickListener(this);
			break;
		default:
			if(Integer.valueOf(deatils.getSERVICE_STATUS())==50){
				//TimeUtil.getTimeByString(deatils.getSERVICE_START(),deatils.getSYSTEMTIME())
				if(Long.valueOf(deatils.getSERVICE_START())<=Long.valueOf(deatils.getSYSTEMTIME())){
					if("0".equals(deatils.getEXTEND_FLAG())){
					Type="DoctorsActiveDelay";
					delayButton.setText("延时服务");//已预约服务（50）+开始服务时间>当前系统时间
					}else{
						delayButton.setVisibility(View.GONE);	
					}
					mView.findViewById(R.id.chat_button).setVisibility(View.VISIBLE);
					mView.findViewById(R.id.chat_button).setOnClickListener(this);
				}
			}else{
				delayButton.setVisibility(View.INVISIBLE);	
			}
			break;
		}
		initData(LOOK_CONTENT);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			getActivity().onBackPressed();
			break;
		case R.id.agree_tuiding://同意退订
			initData(SUMINT_EXIT);
			break;
		case R.id.refuse_tuiding://拒绝退订
			initData(SUMINT_REFUSE);
			break;
		case R.id.refuse_delay_button://拒绝延时请求
			Type="RefusedToDelay";
			delay(deatils.getSERVICE_CUSTOMER_ID(),deatils.getORDER_ID());
			break;
		case R.id.delay_button://同意延时(或者 主动延时)Type=AgreedToDelay
			if(deatils==null)return;
			
			if("".equals(Type)||delayButton.getText().toString().contains("延时服务")){//同意延时(或者 主动延时)
				String str=(!"".equals(deatils.getPATIENT_NAME()))?deatils.getPATIENT_NAME():deatils.getPAY_ACCOUNT();
				DoubleBtnFragmentDialog.showDefault(getChildFragmentManager(),  "您确定将"+str+"的服务时间延长3小时吗？", "取消", "确定", new OnDilaogClickListener() {
					@Override
					public void onDismiss(DialogFragment fragment) {
						fragment.dismissAllowingStateLoss();
					}
					@Override
					public void onClick(DialogFragment fragment, View v) {
						delay(deatils.getSERVICE_CUSTOMER_ID(),deatils.getORDER_ID());
					}
				});
			}else{//停止服务
				
				DoubleBtnFragmentDialog.showDefault(getChildFragmentManager(),  "您确定要停止服务吗?", "取消", "停止", new OnDilaogClickListener() {
					
					@Override
					public void onDismiss(DialogFragment fragment) {
					}
					
					@Override
					public void onClick(DialogFragment fragment, View v) {
						delay(deatils.getSERVICE_CUSTOMER_ID(),deatils.getORDER_ID());
					}
				});
				
				
			}
			break;
		case R.id.service_content:
			Intent intent = new Intent(getActivity(),DoctorServiceActivity.class);
			intent.putExtra("ORIDERID",mOrderId);
			startActivity(intent);
			break;
		case R.id.chat_button:
			CustomerInfoEntity entity=new CustomerInfoEntity();
			entity.setId(mCustomerId);
			entity.setName(mEntity.getCustomerNickname());
			FriendHttpUtil.onItemClick(getActivity(), entity);
			break;
		}
	}
	
	/**
	Type=AgreedToDelay
	ORDER_ID 订单id
	DOCTORID 医生id
	CUSTOMER_ID 客户id
	 */
	protected void delay(String DOCTORID,String ORDER_ID) {
		HttpRestClient.doHttpAgreedToDelay("",Type,SmartFoxClient.getLoginUserId(),deatils.getENJOY_CUSTOMER_ID(),ORDER_ID,new AsyncHttpResponseHandler(getActivity()){
			@Override
			public void onSuccess(String content) {
				try {
					JSONObject object=new JSONObject(content);
					if(object.has("error_message")){
						ToastUtil.showBasicShortToast(getActivity(), object.optString("error_message"));
					}else{
						ToastUtil.showBasicShortToast(getActivity(), "处理成功");
					}
						
				} catch (Exception e) {
//					onFailure(null);
				}
				getActivity().setResult(getActivity().RESULT_OK, getActivity().getIntent());
				getActivity().finish();
			};
		});
	}

	/**
	 * Type=findcustomerBackOrder
		DOCTORID 医生id
		CUSTOMER_ID 客户id
		ORDER_ID 订单id
	 */
	private void initData(String ORDER_ID,String CUSTOMER_ID) {
		HttpRestClient.doHttpLookOrderDetails(ORDER_ID,CUSTOMER_ID,SmartFoxClient.getLoginUserId(),new AsyncHttpResponseHandler(getActivity()){
			
			@Override
			public void onSuccess(String content) {
				if(content.contains("error_message"))return ;
				deatils = DoctorOrderDeatils.parsToEntity(content);
				if(deatils==null){
					onFailure(null);
				}else{
					initDataView(deatils);
				}
			};
			
		} );
	}

	
	/**
	 * 退单时候用的
	 * 
	 * @param type
	 */
	private void initData(final String type) {
		HttpRestClient.doHttpLookDoctorClientExit(mOrderId,SmartFoxClient.getLoginUserId(),mCustomerId,type,new AsyncHttpResponseHandler(getActivity()){
			@Override
			public void onSuccess(int statusCode, String content) {
				try {
					if(type.equals(LOOK_CONTENT)){//查看
						initView(content);
					}else if(type.equals(SUMINT_EXIT)){//同意
						JSONObject object=new JSONObject(content);
						if(object.has("error_message")){
							ToastUtil.showBasicShortToast(getActivity(), object.getString("error_message"));
						}else{
							ToastUtil.showShort(getActivity(), object.getString("message"));
							getActivity().setResult(getActivity().RESULT_OK, getActivity().getIntent());
							getActivity().finish();
							getActivity().overridePendingTransition(R.anim.back_enter, R.anim.back_exit);
						}
					}else{//拒绝
						JSONObject object=new JSONObject(content);
						if(object.has("error_message")){
							ToastUtil.showBasicShortToast(getActivity(), object.getString("error_message"));
						}else{
							ToastUtil.showToastPanl("已拒绝");
							Intent putExtra = getActivity().getIntent();
							putExtra.putExtra("isTrue", true);
							getActivity().setResult(getActivity().RESULT_OK, getActivity().getIntent());
							getActivity().finish();
							getActivity().overridePendingTransition(R.anim.back_enter, R.anim.back_exit);
						}
					}
				} catch (Exception e) {
					onFailure(null);
				}
			}
		});
		
	}
	
	private void initView(String con) {
		try {
			ImageLoader loader=ImageLoader.getInstance();
			JSONObject object=new JSONObject(con);
			mTuiDingContent.setText(object.getString("BACK_REASON"));
			int pics [] = {R.id.pic1,R.id.pic2,R.id.pic3};
			JSONArray jsonArray = object.getJSONArray("PICS");
			for (int i = 0; i < jsonArray.length(); i++) {
				ImageView findView = (ImageView) mView.findViewById(pics[i]);
				findView.setVisibility(View.VISIBLE);
				JSONObject object2 = (JSONObject)jsonArray.get(i);
				final String path=object2.getString("BACK_PIC");
				loader.displayImage(path, findView);
				findView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						ZoomImgeDialogFragment.show(path,getChildFragmentManager());
					}
				});
			}
			TextView contentmesga=(TextView)mView.findViewById(R.id.tuiding_miaoshu);
			contentmesga.setText(object.getString("BACK_MESG"));
		} catch (JSONException e) {
		}
	}
	
}
